<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar :page-no="63" :add-active="addActive" :del-active="delActive" :has-edit="false" :has-save="false" :has-cancel="false" @add="add" @del="del" />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="inventoryRecordName" label="任务名称" />
        <el-table-column prop="warehouseName" label="盘点仓库" />
        <!-- <el-table-column label="查看产品">
          <template v-if="scope.row.inventoryRecordNo" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="checkProduct(scope.row)"><i class="el-icon-view"></i> 查看产品</el-button>
          </template>
        </el-table-column> -->
        <el-table-column prop="personName" label="盘点人" />
        <el-table-column prop="executionDate" label="执行日期" />
        <el-table-column label="盘点结果">
          <template v-if="scope.row.inventoryRecordNo" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="checkResult(scope.row)"><i class="el-icon-view"></i> 查看产品</el-button>
          </template>
        </el-table-column>
        <el-table-column width="140" label="操作">
          <template v-if="scope.row.reason" slot-scope="scope">
            <el-popover
              placement="top-start"
              title="拒绝原因"
              width="200"
              trigger="hover"
              :content="scope.row.reason"
            >
              <el-button slot="reference" class="text-btn-cursor" type="text" size="small">查看原因</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog :title="'盘点记录'" :visible.sync="dialogFormVisible" width="40%" :before-close="cancel">
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="记录名称:" prop="inventoryRecordName" class="w50p">
            <el-input v-model="formData.inventoryRecordName" clearable />
          </el-form-item>
          <el-form-item label="盘点仓库:" prop="warehouseNo" class="w50p">
            <el-select v-model="formData.warehouseNo" clearable filterable @change="getCurrentMaterialValue">
              <el-option
                v-for="item in warehouseList"
                :key="item.warehouseNo"
                :label="item.warehouseName"
                :value="item.warehouseNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="盘点人:" class="w100p" prop="personNo">
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important"
              prop="purchasingDepartmentNo"
            >
              <el-select v-model="formData.purchasingDepartmentNo" clearable @change="getPostList">
                <el-option
                  v-for="(item, index) in departmentList"
                  :key="index.departmentNo"
                  :label="item.departmentName"
                  :value="item.departmentNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="postNo"
            >
              <el-select v-model="formData.postNo" clearable @change="getStaffList">
                <el-option
                  v-for="(item, index) in postList"
                  :key="index.postNo"
                  :label="item.postName"
                  :value="item.postNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="personNo"
            >
              <el-select v-model="formData.personNo" clearable>
                <el-option
                  v-for="(item, index) in staffList"
                  :key="index.personNo"
                  :label="item.person.name"
                  :value="item.personNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="执行日期:" prop="executionDate" class="w50p">
            <el-date-picker v-model="formData.executionDate" align="right" type="date" placeholder="选择日期" />
          </el-form-item>
          <el-form-item label="盘点产品:" prop="product" class="w100p">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 0 10px;"></div>
            <el-checkbox-group v-model="checkedNos" @change="handlecheckedNosChange">
              <el-checkbox v-for="product in productList" :key="product.goodsNo" :label="product.goodsNo">{{ product.goodsName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="盘点详情:" prop="productList" class="w100p">
            <div class="productList">
              <div v-for="(item, index) in curProductList" :key="index" class="product-item">
                <div class="product-name">{{ item.goodsName }}</div>
                <div class="product-value">仓库剩余量: {{ item.residualValue }} {{ item.unitName }}</div>
                <div class="product-inventoryValue">
                  <el-form-item label="盘点后剩余量:" prop="item.inventoryValue" class="w100p">
                    <el-input v-model="item.inventoryValue" />
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog :title="'产品详情'" :visible.sync="dialogProductFormVisible" width="40%">
        <div class="product-detail">
          <div class="title">产品列表：</div>
          <div class="product-list">
            <div v-for="(item, index) in curProductList" :key="index" class="product-item">
              {{ item.goodsName }}
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="closeProduct()">
            关 闭
          </el-button>
        </div>
      </el-dialog>
      <el-dialog :title="'盘点详情'" :visible.sync="dialogResultFormVisible" width="40%">
        <el-form
          ref="formData"
          label-position="left"
          :model="resultFormData"
          class="el-form"
        >
          <el-form-item label="处理日期:" prop="executionDate" class="w100p">
            <el-date-picker v-model="resultFormData.executionDate" disabled align="right" type="date" placeholder="选择日期" />
          </el-form-item>
          <el-form-item label="盘点详情:" prop="curProductList" class="w100p">
            <div class="productList">
              <div v-for="(item, index) in curProductList" :key="index" class="product-item">
                <div class="product-name">{{ item.goodsName }}</div>
                <div class="product-value">仓库剩余量: {{ item.residualValue }} {{ item.unitName }}</div>
                <div class="product-inventoryValue">
                  <el-form-item label="盘点后剩余量:" prop="item.inventoryValue" class="w100p">
                    <el-input v-model="item.inventoryValue" disabled />
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="closeResult()">
            关 闭
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-operation/warehouse-check";
import warehouseManage from "@/api/basic-info-manage/warehouse-manage";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot"
import staffManage from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";

import { mymixin } from "@/utils/mixin"
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "check-record",
  components: { SearchForm, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '任务名称',
          prop: 'inventoryTaskName',
          type: 'input',
        }, {
          label: '盘点仓库',
          prop: 'warehouseNo',
          type: 'select',
          options: [], // warehouseList
          optionKey: { label: 'warehouseName', value: 'warehouseNo' },
        }, {
          label: '盘点人',
          prop: 'personNo',
          type: 'select',
          options: [], // personList
          optionKey: { label: 'personName', value: 'personNo' },
        }, {
          label: '执行日期',
          prop: 'executionDate',
          type: 'date',
        }, 
      ],
      searchlist: {},
      // 部门岗位员工列表
      departmentList: [],
      postList: [],
      staffList: [],
      isIndeterminate: false,
      checkedNos: [],
      checkAll: true,
      formData: {},
      warehouseList: [],
      productList: [],
      personList: [],
      curProductList: [],
      saveActive: false,
      rules: {
        inventoryRecordName: [
          { required: true, message: "请输入任务名称", trigger: "change" }
        ]
      },
      resultFormData: {},
      dialogProductFormVisible: false,
      dialogResultFormVisible: false,
      selectedList: []
    };
  },
  watch: {},
  created() {
    // 获取表格数据
  },
  mounted() {
    this.getDepartmentList();
    this.getWarehouseList();
    this.getPersonList();
    this.getTableDataList();
  },
  methods: {
    getTableDataList() {
      console.log(this.searchlist)
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchlist
        }
      };
      nowpagereq.queryRecordPageByPersonNo(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error('查询失败')
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.addblankmet()
        this.resetActionBar();
      });
    },

    handleSelectionChange(list) {
      this.selectedList = [];
      this.selectedList = list.map(item => {
        if (item.unitNo) {
          return item.unitNo
        } else {
          return ""
        }
      });
    },
    delmessage() {
      nowpagereq.delPlantingUnitById(this.selectedList).then(
        res => {
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.getTableDataList();
          } else {
            this.$message.error('删除失败')
          }
        }
      )
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    getCurrentMaterialValue(no) {
      nowpagereq.getCurrentMaterialValue({ warehouseNo: no }).then(res => {
        this.productList = res.data;
      })
    },
    getWarehouseList() {
      let params = { entity: {} };
      warehouseManage.getWareHouseListByCondition(params).then(res => {
        this.warehouseList = res.data;
        this.formConfig[1].options = res.data;
      })
    },
    getPersonList() {
      // let params = { entity: {} };
      staffManage.getStaffListByCondition().then(res => {
        this.personList = res.data;
        this.formConfig[2].options = res.data.map(el => {
          return { ...el, personName: el.person.name }
        })
      })
    },
    // 获取部门列表
    getDepartmentList() {
      managementtwo.getDepartmentList().then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.code != 1) {
          return;
        }
        this.departmentList = res.data;
      })
    },
    getPostList(no) {
      managementtwo.getPostList(no).then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.code != 1) {
          return;
        }
        this.postList = res.data;
      })
    },
    getStaffList(no) {
      managementtwo.getEmployeeList(no).then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.code != 1) {
          return;
        }
        this.staffList = res.data;
      });
    },
    // 多选框选择方法
    handleCheckAllChange(val) {
      console.log(val)
      if (val) {
        this.checkedNos = this.productList.map(
          item => {
            return item.goodsNo
          }
        )
      } else {
        this.checkedNos = []
      }
      this.isIndeterminate = false;
      this.dealCurProductList();
    },

    handlecheckedNosChange(value) {
      console.log(value, 'value');
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.productList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.productList.length;
      this.dealCurProductList();
    },
    dealCurProductList() {
      let that = this;
      let list = [];
      that.checkedNos.forEach(item => {
        // eslint-disable-next-line eqeqeq
        let obj = that.productList.find(el => el.goodsNo == item);
        obj.residualValue = obj.value;
        list.push(obj);
      })
      that.curProductList = list;
    },
    save() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.formData));
          params.recordCargoMapperList = this.curProductList;
          if (!params.recordCargoMapperList.length) {
            this.$message.error('请选择盘点产品')
            return;
          }
          // 新增接口
          nowpagereq.addRecordAlone(params).then(res => {
            if (res.code === 1) {
              this.$message.success("新增成功！");
              this.closeDialog();
              this.getTableDataList();
            } else {
              this.$message.error("新增失败！");
            }
          });
        }
      })
    },
    checkResult(row) {
      if (row.inventoryRecordNo) {
        this.resultFormData = row;
        this.dialogResultFormVisible = true;
        nowpagereq.getInventoryRecord(row.inventoryRecordNo).then(result => {
          this.curProductList = result.data;
        });
      }
    },
    closeResult() {
      this.curProductList = [];
      this.dialogResultFormVisible = false;
    },
    checkProduct(row) {
      if (row.inventoryRecordNo) {
        this.dialogProductFormVisible = true;
        nowpagereq.queryAllByInventoryTaskNo(row.inventoryRecordNo).then(result => {
          this.curProductList = result.data;
        });
      }
    },
    closeProduct() {
      this.curProductList = [];
      this.dialogProductFormVisible = false;
    },

    closeDialog() {
      this.dialogFormVisible = false;
      this.nowChanceStau = '';
      this.curProductList = [];
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
.df {
  display: flex;
  align-items: center;
  width: 100%;
}

.dfs {
  ::v-deep .el-form-item__content {
    flex-direction: column;
  }
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
}

.tags {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .tag-item {
    height: 30px;
    padding: 5px 10px;
    background-color: #00a1c2;
    border-radius: 8px;
    display: flex;
    align-items: center;
    margin-top: 10px;
    margin-right: 10px;

    i {
      font-size: 14px;
    }
  }
}
.productList{

  .product-item{
    display: flex;
    margin-bottom: 10px;
    .product-name{
      width: 120px;
      flex-shrink: 0;
      font-size: 16px;
    }
    .product-value{
      font-size: 16px;
      width: 200px;
      flex-shrink: 0;
    }
    .product-inventoryValue{
      width: 100%;
    }
  }
}
.product-detail{
  .title{
    font-size: 16px;
    font-weight: bold;
  }
  .product-list{
    display: flex;
    flex-wrap: wrap;

    .product-item{
      background: #00a1c2;
      color: #fff;
      text-align: center;
      padding: 8px 24px;
      margin: 10px 20px 0 0;
      border-radius: 8px;
    }
  }
}

.action-bar {
  width: 100%;
  height: $actionBarHeight;
  background-color: $hamburgerBgColor;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 10px;
  .btn-list {
    display: flex;
    align-items: center;
    img {
      height: 30px;
      margin-right: 15px;
      cursor: pointer;
    }
  }
}

.form-data{
  width: 100%;
  .el-input__inner {
    color: #000;
    border-color: rgba(217, 217, 217, 1);
    background-color: rgba(255, 255, 255, 1);
  }

  .el-textarea__inner {
    color: #000;
    border-color: rgba(217, 217, 217, 1);
    background-color: rgba(255, 255, 255, 1);
  }

  .el-form {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      display: flex;
      align-items: flex-start;

      .el-form-item__label {
        line-height: 36px;
        min-width: 120px;
        text-align: end;
        flex-shrink: 0;
      }

      ::v-deep .el-form-item__content {
        line-height: 36px;
        width: 100%;
        display: flex;
        // flex-direction: row;
        flex-wrap: wrap;
      }

      ::v-deep .el-checkbox__label{
        color: #ccc;
      }
    }
  }
}
</style>
